<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Contacts as ContactsModel;
use addons\qingdong\model\ContactsFile;
use addons\qingdong\model\ContactsOther;
use addons\qingdong\model\FormField;
use addons\qingdong\model\Record;
use addons\qingdong\model\Event as EventModel;
use addons\qingdong\model\OperationLog;
use addons\qingdong\model\Staff;
use think\Db;
use think\Exception;

/**
 * 联系人接口
 */
class Contacts extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//创建联系人
	public function addContacts() {
		$params = $this->request->post();
		if (empty($params['contacts'])) {
			$this->error('联系人信息不能为空');
		}
		// 表单验证
        if (($result = $this->qingdongValidate($params['contacts'], get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params['contacts']);
        if ($result !== true) {
            $this->error($result);
        }
		if (ContactsModel::where([
			'mobile'      => $params['contacts']['mobile'],
			'customer_id' => $params['contacts']['customer_id']
		])->find()) {
			$this->error('联系人手机号已存在');
		}
		Db::startTrans();
		try {
			$mobile =$params['contacts']['mobile'];
			$email =$params['contacts']['email']??'';
			if(empty($mobile) && empty($email)){
				$this->error('手机号码和邮箱至少填写一项！');
			}
			$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
			$rule2 = '^[0-9]+$^';
			if (preg_match($rule, $mobile) == false && preg_match($rule2, $mobile) ==false) {
				$this->error('手机号格式错误，国外手机号请填写区号,例如 86XXXX');
			}

            $contactsId = ContactsModel::createContacts($params['contacts']);
			if (isset($params['is_event']) && $params['is_event'] == 1) {//跟进任务
				$event                  = $params['event'];
				$event['type']          = 2;//任务
				$event['relation_type'] = EventModel::CONTACTS_TYPE;//联系人
				$event['relation_id']   = $contactsId;
				$event['end_time']      = $event['start_time'];
				$event['level']         = 1;
				$result                 = EventModel::createEvent($event);
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('创建联系人成功');
		}
	}


	//编辑联系人
	public function editContacts() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ContactsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('客户信息不存在');
		}
		// 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		if (ContactsModel::where([
			'mobile'      => $params['mobile'],
			'customer_id' => $row['customer_id'],
			'id'          => ['neq', $params['id']]
		])->find()) {
			$this->error('联系人手机号已存在');
		}
		Db::startTrans();
		try {
			$result = ContactsModel::updateContacts($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('编辑联系人成功');
	}


	//删除联系人
	public function delContacts() {
		$id = input('id');

		$row = ContactsModel::where(['id' => $id, 'owner_staff_id' => $this->auth->id])->find();
		if (empty($row)) {
			$this->error('您不是客户归属人，无法删除当前联系人');
		}
		$model = new ContactsModel();
		if ($model->destroy(['id' => $id])) {
			$this->success('删除成功');
		}
		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $row['customer_id'],
            '删除联系人:' . $row['name']);
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $row['customer_id'], '删除联系人:' . $row['name']);
		$this->error('删除失败');
	}


	//获取联系人列表
	public function getList() {
		$limit       = input("limit/d", 10);
		$customer_id = input('customer_id');
		$name        = input('name');

        $params = input();
        $where = FormField::updateWhereField(FormField::CONTACTS_TYPE, $params);
        if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}else{
			$where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
		}
		if ($name) {
			$where['name'] = ['like', "%{$name}%"];
		}
		$records                 = ContactsModel::where($where)->with(['customer'])->order('id desc')->paginate($limit);
		$this->success('请求成功', $records);
	}


	//获取select联系人列表
	public function getSelectList() {
		$customer_id = input('customer_id');
        $name = input('name','');
		$where       = [];
		if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}
        if ($name) {
            $where['name'] = ['like',"%$name%"];
        }
		$list                    = ContactsModel::where($where)->with(['customer'])->field('id,customer_id,name,mobile')->select();
		$list                    = collection($list)->toArray();
		foreach ($list as $k => $v) {
			$v['new_mobile'] = $v['mobile'];
			$list[$k]        = $v;
		}
		$this->success('请求成功', $list);
	}


	//获取联系人详情
	public function getDetail() {
		$id       = input('id');
		$contract = ContactsModel::where(['id' => $id])->with([
			'customer',
			'ownerStaff'
		])->find();

		if (empty($contract)) {
			$this->error('信息不存在');
		}
		$contract               = $contract->toArray();
        $contract=ContactsOther::getOther($contract);

		$this->success('请求成功', $contract);
	}


	//获取附件列表
	public function getFilesList() {
		$id = input('contacts_id');

		$files = ContactsFile::where(['contacts_id' => $id])->field('file_id')->with(['file'])->select();
		$this->success('请求成功', $files);
	}
}
